#include <iostream>
#include <fstream>
#include <string>

using namespace std;

void resolve(ofstream& file,ifstream& log);
void handle_line(ofstream& file,string& line,size_t& pos);

int main(){
	ofstream file("TimeTemp.csv");
	string LogPath;
	cout<<"pls input file path: "<<endl;
	// 如果文件路径中包含空格，则cin无法读入完整路径
	// cin>>LogPath;
	getline(cin,LogPath);
	ifstream log(LogPath);
	if(file.is_open()&&log.is_open()){
        	file<<"time,temp,brightness,is_charge"<<endl;
		resolve(file,log);
	}
	else{
		cout<<"\033[31m"<<"Error creating (or opening) file."<<"\033[0m"<<endl;
	}
}

void resolve(ofstream& file,ifstream& log){
	log.seekg(0,ios::beg);
	string line;
	while(getline(log,line)){
		size_t pos_temp=line.find("][VIRTUAL");
		// 如果没找到关键字则此行不用分析
		if(pos_temp==string::npos){
			continue;
		}
		// 找到关键字则分析此行
		else{
			// 所有操作在handle_line函数中完成，参数有输出file、当前line、位置pos
			handle_line(file,line,pos_temp);
			/* to be delete
            		file<<time<<","<<temp<<endl;
			*/
		}
	}
}
 
void handle_line(ofstream& file,string& line,size_t& pos){
	if(line[8]==':' && line[11]==':'){
		string time;
		int temp;
		// string类型是为了防止万一在该行找不到相应字段，则置空方便
		string brightness="";
		bool is_charge="";
		// time包含日期和时间格式：mm-dd hh:mm:ss
		time=line.substr(0,14);
		string temp_str=line.substr(pos+18,5);
		temp=stoi(temp_str);

		// 原生代码中brightness单词拼写有误，将错就错
		// size_t和size_type类似，但是string::find()源码中参数类型的size_type
		size_t pos_bright_beg=line.find("[brigntness");
		size_t pos_bright_end=line.find("]",pos_bright_beg);

		brightness=line.substr(pos_bright_beg+12,pos_bright_end-pos_bright_beg-12);
		size_t pos_current=line.find("][current");
		is_charge=line[pos_current+10]=='-'?true:false;

		// 在handle_line中执行写文件操作
		file<<time<<","<<temp<<","<<brightness<<","<<is_charge<<endl;
	}
	else{
		file<<"format error"<<endl;
	}

}
